#include <avr/io.h>
#include <avr/interrupt.h>
#include "usart.h"
#include "cache.h"

ISR(USART_RXC_vect)
{
 unsigned char byte;
 byte = UDR;
 if(byte != 0xA) //Parser Line Feed(LF)
  backNumber = NewToCache(get, ARRAYSIZE, byte);

 if(backNumber == (ARRAYSIZE-1))
 {
  while(backNumber != 0)
  {
   USend(NextInCache(get, ARRAYSIZE));
   backNumber--;
  }
 }

}

void UInit()
{
 backNumber = 0;
 // Set baud rate
 UBRRH = 0; //(USART_UBBR_VALUE>>8);
 UCSRA=(1<<U2X); //Optimizing
// UBRRL = (uint8_t)USART_UBBR_VALUE;
 UBRRL = 3; //Setting to 115.2k bit/s 8 data bits, no parity, 1 stop bit
 // Enable receiver and transmitter
 UCSRB = (1<<RXEN)|(1<<TXEN);
 //Receiver interrupt enable
 UCSRB |= (1 << RXCIE);
}

void USend(unsigned char data)
{
 // Wait if a byte is being transmitted
 while((UCSRA&(1<<UDRE)) == 0);
 // Transmit data
 UDR = data;
}

unsigned char UReceive()
{
 // Wait until a byte has been received
 while((UCSRA&(1<<RXC)) == 0);
 // Return received data
 return UDR;
}

void USendStr(unsigned char *pData)
{
 do {
  USend(*pData++);
 } while(*pData != '\0');
}
/*
void UReceiveStr(unsigned char *data, unsigned char size)
{
 unsigned char idx = 0;
 do {
  data[idx] = UReceive();
 } while( (idx != (size -1)) || (data[idx] == 0xD) || (data[idx] == 0xA)|| (data[idx] == '\0') || (idx == (size-1)));

 if(idx == size)
  idx = idx -1;

 data[idx] = 0;
 idx = 0;
}
*/
void UReceiveStr(unsigned char *data, unsigned char size)
{
 unsigned char idx = 0;
 unsigned char receive;
 
 do {
 receive = UReceive();

 if(receive == 0xA)
  break;

 NewToCache(data, size, receive);
 idx++;
 } while( idx < size );
 data[idx] = 0;
 idx = 0;
}
